<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" label-position="left">
      <el-form-item label="商品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类型" prop="productType">
        <el-cascader
          v-model="queryParams.productType"
          :options="typeTreeData"
          :props="{
            checkStrictly: true,
            value: 'id',
            label: 'name',
            children: 'children',
            emitPath: false,
            expandTrigger: 'hover'
          }"
          placeholder="请选择商品类型"
          clearable
          filterable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input
          v-model="queryParams.contactInfo"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supply:authentication:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supply:authentication:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supply:authentication:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supply:authentication:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="authenticationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="ID" />
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品图片" align="center" prop="productImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.productImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="productType">
        <template slot-scope="scope">
          <span>{{ getTypeName(scope.row.productType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品品牌" align="center" prop="productBrand" />
      <el-table-column label="认证状态" align="center" prop="authStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.auth_status_type" :value="scope.row.authStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="认证机构" align="center" prop="authAgency" />
      <el-table-column label="认证书编号" align="center" prop="authCertificateNumber" />
      <el-table-column label="认证有效期" align="center" prop="authValidity" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.authValidity, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="认证批准" align="center" prop="authApproval" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column label="联系方式" align="center" prop="contactInfo" />
      <el-table-column label="合作历史" align="center" prop="cooperationHistory" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supply:authentication:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supply:authentication:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品认证对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="productImage">
          <image-upload v-model="form.productImage"/>
        </el-form-item>
        <el-form-item label="商品类型" prop="productType">
          <el-cascader
            v-model="form.productType"
            :options="typeTreeData"
            :props="{
              checkStrictly: true,
              value: 'id',
              label: 'name',
              children: 'children',
              emitPath: false,
              expandTrigger: 'hover'
            }"
            placeholder="请选择商品类型"
            class="full-width"
            clearable
            filterable
            ref="typeCascader"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品品牌" prop="productBrand">
          <el-input v-model="form.productBrand" placeholder="请输入商品品牌" />
        </el-form-item>
        <el-form-item label="认证状态" prop="authStatus">
          <el-select v-model="form.authStatus" placeholder="请选择认证状态">
            <el-option
              v-for="dict in dict.type.auth_status_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="认证机构" prop="authAgency">
          <el-input v-model="form.authAgency" placeholder="请输入认证机构" />
        </el-form-item>
        <el-form-item label="认证书编号" prop="authCertificateNumber">
          <el-input v-model="form.authCertificateNumber" placeholder="请输入认证书编号" />
        </el-form-item>
        <el-form-item label="认证有效期" prop="authValidity">
          <el-date-picker clearable
            v-model="form.authValidity"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择认证有效期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="认证批准" prop="authApproval">
          <el-input v-model="form.authApproval" placeholder="请输入认证批准" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactInfo">
          <el-input v-model="form.contactInfo" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="合作历史" prop="cooperationHistory">
          <el-input v-model="form.cooperationHistory" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAuthentication, getAuthentication, delAuthentication, addAuthentication, updateAuthentication } from "@/api/supply/authentication";
import { fetchCategoryTree } from "@/api/official";

export default {
  name: "Authentication",
  dicts: ['product_type', 'auth_status_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品认证表格数据
      authenticationList: [],
      // 商品类型树数据
      typeTreeData: [],
      // 第三级商品类型列表
      thirdLevelTypes: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        productName: null,
        productImage: null,
        productType: null,
        productBrand: null,
        authStatus: null,
        authAgency: null,
        authCertificateNumber: null,
        authValidity: null,
        authApproval: null,
        supplierName: null,
        contactInfo: null,
        cooperationHistory: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "商品ID不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getTypeTree();
    this.getList();
  },
  methods: {
    /** 获取商品类型树 */
    getTypeTree() {
      console.log('调用TypeTree接口获取商品类型');
      
      // 使用硬编码的商品类型数据，确保有基本数据显示
      const staticTypeData = [
        {
          id: 1,
          name: '备品备件',
          children: [
            { id: 4, name: '工厂自动化' },
            { id: 28, name: '低压配电' },
            { id: 36, name: '气动液压' },
            { id: 65, name: '动力传动' },
            { id: 76, name: '电线电缆' }
          ]
        },
        {
          id: 357,
          name: '办公用品',
          children: [
            { id: 358, name: '文具' },
            { id: 359, name: '办公设备' }
          ]
        },
        {
          id: 373,
          name: '百货个护',
          children: [
            { id: 374, name: '家居装饰' },
            { id: 375, name: '美妆护肤' },
            { id: 376, name: '小家电' },
            { id: 377, name: '个人护理' },
            { id: 378, name: '家用百货' }
          ]
        }
      ];
      
      // 初始使用静态数据
      this.typeTreeData = staticTypeData;
      
      // 提取所有类型到列表
      this.extractThirdLevelTypes(this.typeTreeData);
      
      // 从API获取真实数据
      fetchCategoryTree().then(response => {
        try {
          // 获取API返回的数据
          const rawData = response.data || response;
          
          // 使用专门的处理函数处理TypeTree格式的数据
          const processedTypeTree = this.processTypeTreeData(rawData);
          
          // 如果成功处理出数据，则更新本地数据
          if (processedTypeTree && processedTypeTree.length > 0) {
            this.typeTreeData = processedTypeTree;
            
            // 更新分类列表
            this.extractThirdLevelTypes(this.typeTreeData);
            
            // 重新渲染级联选择器
            this.$nextTick(() => {
              if (this.$refs.typeCascader) {
                console.log('强制刷新级联选择器');
                this.$refs.typeCascader.$forceUpdate();
              }
            });
          }
        } catch (error) {
          console.error('处理API返回数据出错:', error);
        }
      }).catch(error => {
        console.error('调用TypeTree API失败:', error);
      });
    },
    /** 从类型树数据中提取所有层级类型 */
    extractThirdLevelTypes(treeData) {
      this.thirdLevelTypes = [];
      
      if (!treeData || treeData.length === 0) return;
      
      // 递归提取所有层级的类型
      const extractAllLevels = (nodes, parentPath = '') => {
        if (!nodes || !Array.isArray(nodes)) return;
        
        nodes.forEach(node => {
          if (!node) return;
          
          const id = typeof node.id === 'string' ? parseInt(node.id, 10) : (node.id || 0);
          const name = node.name || node.label || '未命名类型';
          const fullPath = parentPath ? `${parentPath} > ${name}` : name;
          
          // 添加当前节点到类型列表
          this.thirdLevelTypes.push({
            id: id,
            name: name,
            fullPath: fullPath
          });
          
          // 递归处理子节点
          if (node.children && node.children.length > 0) {
            extractAllLevels(node.children, fullPath);
          }
        });
      };
      
      // 开始递归处理
      extractAllLevels(treeData);
      
      // 确保至少有一条数据
      if (this.thirdLevelTypes.length === 0) {
        this.thirdLevelTypes.push({
          id: 0,
          name: '默认类型',
          fullPath: '默认类型'
        });
      }
    },
    /** 处理类型树数据，确保结构正确 */
    processTypeTreeData(rawData) {
      // 检查数据是否有效
      if (!rawData || !Array.isArray(rawData) || rawData.length === 0) {
        return null;
      }
      
      // 创建处理结果数组 - 存储一级类目
      let processedData = [];
      
      // 遍历每一个一级类目项
      rawData.forEach(item => {
        if (!item || !item.firstCatalog) return;
        
        // 获取一级类目信息
        const firstCatalog = item.firstCatalog;
        
        // 创建一级类目节点
        const level1Node = {
          id: firstCatalog.id,
          name: firstCatalog.name,
          children: []
        };
        
        // 处理二级类目 - 来自childrenCatalog数组
        if (item.childrenCatalog && Array.isArray(item.childrenCatalog)) {
          // 只处理与当前一级类目关联的二级类目
          const level2Items = item.childrenCatalog.filter(l2 => 
            l2.parentId === firstCatalog.id || 
            l2.level === 2
          );
          
          level2Items.forEach(level2Item => {
            // 创建二级类目节点
            const level2Node = {
              id: level2Item.id,
              name: level2Item.name,
              children: []
            };
            
            // 处理三级类目 - 通常在二级类目的children中
            if (level2Item.children && Array.isArray(level2Item.children)) {
              // 筛选出确实是三级的项目
              const level3Items = level2Item.children.filter(l3 => 
                l3.parentId === level2Item.id || 
                l3.level === 3
              );
              
              level3Items.forEach(level3Item => {
                // 添加三级类目节点
                level2Node.children.push({
                  id: level3Item.id,
                  name: level3Item.name
                });
              });
            }
            
            // 只有当有三级节点时才保留children属性
            if (level2Node.children.length === 0) {
              delete level2Node.children;
            }
            
            // 添加二级节点到一级节点的children中
            level1Node.children.push(level2Node);
          });
        }
        
        // 只有当有二级节点时才保留children属性
        if (level1Node.children.length === 0) {
          delete level1Node.children;
        }
        
        // 添加一级节点到结果数组
        processedData.push(level1Node);
      });
      
      return processedData.length > 0 ? processedData : null;
    },
    /** 根据类型ID获取类型名称 */
    getTypeName(typeId) {
      if (typeId === undefined || typeId === null) return '未知类型';
      
      // 转换ID类型，便于多种匹配方式
      const typeStr = String(typeId);
      let typeNum = Number(typeId);
      if (isNaN(typeNum)) typeNum = 0;
      
      // 尝试在提取的类型列表中查找
      const matchingType = this.thirdLevelTypes.find(t => 
        t.id === typeId ||             // 完全匹配
        t.id === typeNum ||            // 数字类型匹配
        String(t.id) === typeStr       // 字符串匹配
      );
      
      // 如果找到匹配，返回类型名称
      if (matchingType) {
        return matchingType.name;
      }
      
      // 尝试从旧的字典中查找
      const found = this.dict.type.product_type.find(d => d.value === typeId || d.value === typeStr);
      if (found) return found.label;
      
      // 如果仍找不到，返回ID信息
      return `类型(${typeId})`;
    },
    /** 查询商品认证列表 */
    getList() {
      this.loading = true;
      listAuthentication(this.queryParams).then(response => {
        this.authenticationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ID: null,
        productId: null,
        productName: null,
        productImage: null,
        productType: null,
        productBrand: null,
        authStatus: null,
        authAgency: null,
        authCertificateNumber: null,
        authValidity: null,
        authApproval: null,
        supplierName: null,
        contactInfo: null,
        cooperationHistory: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ID)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品认证";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.ID || this.ids
      getAuthentication(ID).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品认证";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ID != null) {
            updateAuthentication(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAuthentication(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.ID || this.ids;
      this.$modal.confirm('是否确认删除商品认证编号为"' + IDs + '"的数据项？').then(function() {
        return delAuthentication(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supply/authentication/export', {
        ...this.queryParams
      }, `authentication_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
/* 级联选择器样式 */
::v-deep .el-cascader {
  width: 100% !important;
  
  .el-input__inner {
    height: 32px;
    line-height: 32px;
    padding-right: 30px;
  }
  
  .el-input__suffix {
    right: 5px;
    top: 1px;
    pointer-events: auto;
  }
  
  .el-cascader__dropdown {
    z-index: 3000 !important; /* 确保级联下拉框在最顶层 */
  }
}

/* 确保下拉菜单可见 */
::v-deep .el-select-dropdown, ::v-deep .el-cascader-menus {
  z-index: 3000 !important;
  visibility: visible !important;
  display: block !important;
  position: absolute !important;
  opacity: 1 !important;
}

/* 确保下拉菜单的项目可点击 */
::v-deep .el-cascader-menu__item {
  padding: 8px 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  box-sizing: border-box;
  cursor: pointer;
  outline: none;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  &.is-active {
    color: #409EFF;
    font-weight: 700;
  }
}

.full-width {
  width: 100%;
}
</style>
